import { Content } from '../../types/document';
import { 
  SearchService as ISearchService,
  SearchConfig, 
  SearchResult, 
  SearchFilters,
  SearchHistory,
  SearchServiceResult,
  SEARCH_STORAGE_KEYS,
  SEARCH_LIMITS
} from './types';
import { FullTextSearchEngine } from './fullTextSearchEngine';
import { FilterProcessor } from './filterProcessor';
import { simpleStorageAdapter } from '../export/simpleStorageAdapter';

export class SearchService implements ISearchService {
  private searchEngine: FullTextSearchEngine;
  private filterProcessor: FilterProcessor;
  private searchHistoryCache: SearchHistory[] = [];

  constructor() {
    this.searchEngine = new FullTextSearchEngine();
    this.filterProcessor = new FilterProcessor();
  }

  /**
   * 执行搜索
   */
  async search(config: SearchConfig): Promise<SearchServiceResult<SearchResult[]>> {
    try {
      const startTime = Date.now();
      
      // 验证搜索配置
      const validationError = this.validateSearchConfig(config);
      if (validationError) {
        return { success: false, error: validationError };
      }

      // 获取所有文档（这里需要从文档服务获取）
      const documents = await this.getAllDocuments();
      
      // 应用筛选条件
      const filteredDocuments = await this.filterProcessor.applyFilters(documents, config.filters);
      
      // 执行全文搜索
      const results = await this.searchEngine.search(filteredDocuments, config);
      
      // 限制结果数量
      const limitedResults = results.slice(0, SEARCH_LIMITS.MAX_RESULTS);
      
      // 记录搜索历史
      const searchTime = Date.now() - startTime;
      await this.addSearchHistory(config.query, config.filters, limitedResults.length, searchTime);
      
      console.log(`[SearchService] 搜索完成: 查询="${config.query}", 结果=${limitedResults.length}个, 耗时=${searchTime}ms`);
      
      return { 
        success: true, 
        data: limitedResults 
      };

    } catch (error) {
      console.error('[SearchService] 搜索失败:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '搜索失败' 
      };
    }
  }

  /**
   * 获取搜索建议
   */
  async getSuggestions(query: string): Promise<string[]> {
    try {
      if (!query.trim() || query.length < 2) return [];
      
      return await this.searchEngine.getSuggestions(query);
    } catch (error) {
      console.error('[SearchService] 获取搜索建议失败:', error);
      return [];
    }
  }

  /**
   * 获取搜索历史
   */
  async getSearchHistory(): Promise<SearchHistory[]> {
    try {
      if (this.searchHistoryCache.length > 0) {
        return this.searchHistoryCache;
      }

      const result = await simpleStorageAdapter.get<SearchHistory[]>(SEARCH_STORAGE_KEYS.SEARCH_HISTORY);
      if (result.success && result.data) {
        this.searchHistoryCache = result.data.sort((a, b) => b.timestamp - a.timestamp);
      }
      
      return this.searchHistoryCache;
    } catch (error) {
      console.error('[SearchService] 获取搜索历史失败:', error);
      return [];
    }
  }

  /**
   * 添加搜索历史
   */
  async addSearchHistory(
    query: string, 
    filters: SearchFilters, 
    resultCount: number,
    searchTime: number = 0
  ): Promise<void> {
    try {
      // 如果查询为空，不记录历史
      if (!query.trim()) return;

      const history = await this.getSearchHistory();
      
      // 检查是否已存在相同的搜索
      const existingIndex = history.findIndex(h => 
        h.query === query && JSON.stringify(h.filters) === JSON.stringify(filters)
      );
      
      const newHistoryItem: SearchHistory = {
        id: this.generateId(),
        query,
        filters,
        resultCount,
        searchTime,
        timestamp: Date.now()
      };

      if (existingIndex >= 0) {
        // 更新现有记录
        history[existingIndex] = newHistoryItem;
      } else {
        // 添加新记录
        history.unshift(newHistoryItem);
      }

      // 限制历史记录数量
      const limitedHistory = history.slice(0, SEARCH_LIMITS.MAX_SEARCH_HISTORY);
      
      // 保存到存储和缓存
      this.searchHistoryCache = limitedHistory;
      await simpleStorageAdapter.set(SEARCH_STORAGE_KEYS.SEARCH_HISTORY, limitedHistory);
      
    } catch (error) {
      console.error('[SearchService] 添加搜索历史失败:', error);
    }
  }

  /**
   * 清除搜索历史
   */
  async clearSearchHistory(): Promise<void> {
    try {
      this.searchHistoryCache = [];
      await simpleStorageAdapter.set(SEARCH_STORAGE_KEYS.SEARCH_HISTORY, []);
      console.log('[SearchService] 搜索历史已清除');
    } catch (error) {
      console.error('[SearchService] 清除搜索历史失败:', error);
    }
  }

  /**
   * 重建搜索索引
   */
  async rebuildIndex(): Promise<void> {
    try {
      console.log('[SearchService] 开始重建搜索索引...');
      const documents = await this.getAllDocuments();
      await this.searchEngine.rebuildIndex(documents);
      console.log('[SearchService] 搜索索引重建完成');
    } catch (error) {
      console.error('[SearchService] 重建搜索索引失败:', error);
      throw error;
    }
  }

  /**
   * 更新文档索引
   */
  async updateDocumentIndex(document: Content): Promise<void> {
    try {
      await this.searchEngine.updateDocumentIndex(document);
    } catch (error) {
      console.error('[SearchService] 更新文档索引失败:', error);
    }
  }

  /**
   * 删除文档索引
   */
  async removeDocumentIndex(documentId: string): Promise<void> {
    try {
      await this.searchEngine.removeDocumentIndex(documentId);
    } catch (error) {
      console.error('[SearchService] 删除文档索引失败:', error);
    }
  }

  /**
   * 验证搜索配置
   */
  private validateSearchConfig(config: SearchConfig): string | null {
    if (config.query.length > SEARCH_LIMITS.MAX_QUERY_LENGTH) {
      return `搜索查询长度不能超过${SEARCH_LIMITS.MAX_QUERY_LENGTH}个字符`;
    }

    if (config.filters.dateRange) {
      const { start, end } = config.filters.dateRange;
      if (start > end) {
        return '开始时间不能晚于结束时间';
      }
    }

    if (config.filters.minSize && config.filters.maxSize) {
      if (config.filters.minSize > config.filters.maxSize) {
        return '最小大小不能大于最大大小';
      }
    }

    return null;
  }

  /**
   * 获取所有文档（临时实现，实际应该从文档服务获取）
   */
  private async getAllDocuments(): Promise<Content[]> {
    try {
      // 从存储中获取所有文档
      const documents: Content[] = [];
      
      // 获取最近文档列表
      const recentResult = await simpleStorageAdapter.get<string[]>('rmzf:recent:documents');
      if (recentResult.success && recentResult.data) {
        for (const docId of recentResult.data) {
          try {
            // 尝试获取文档内容
            const docResult = await simpleStorageAdapter.get<Content>(`rmzf:content:text:${docId}`);
            if (docResult.success && docResult.data) {
              documents.push(docResult.data);
            }
          } catch (error) {
            console.warn('[SearchService] 获取文档失败:', docId, error);
          }
        }
      }
      
      return documents;
    } catch (error) {
      console.error('[SearchService] 获取文档列表失败:', error);
      return [];
    }
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return `search_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}

// 导出服务单例
let searchServiceInstance: SearchService | null = null;

export function createSearchService(): SearchService {
  if (!searchServiceInstance) {
    searchServiceInstance = new SearchService();
  }
  return searchServiceInstance;
}

export const searchService = createSearchService();